package utils

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"io/ioutil"
	"net/http"
	"strings"
)

const API_KEY = "nHSpzSGG8G96Cbl3KEkAYtKl"
const SECRET_KEY = "YTtyepa5CHuSPa2ycAcG9aVLFq2PdIpj"

type Text struct {
	Conclusion string `json:"conclusion"`
	LogId      int64  `json:"log_id"`
	Data       []struct {
		Msg        string `json:"msg"`
		Conclusion string `json:"conclusion"`
		Hits       []struct {
			WordHitPositions []struct {
				Positions [][]int `json:"positions"`
				Label     string  `json:"label"`
				Keyword   string  `json:"keyword"`
			} `json:"wordHitPositions"`
			Probability       float64     `json:"probability"`
			DatasetName       string      `json:"datasetName"`
			Words             []string    `json:"words"`
			ModelHitPositions [][]float64 `json:"modelHitPositions"`
		} `json:"hits"`
		SubType        int `json:"subType"`
		ConclusionType int `json:"conclusionType"`
		Type           int `json:"type"`
	} `json:"data"`
	IsHitMd5       bool `json:"isHitMd5"`
	ConclusionType int  `json:"conclusionType"`
}

func BaiduText(data string) Text {
	var t Text
	url := "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + GetAccessToken()
	payload := strings.NewReader("text=" + data)
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, payload)

	if err != nil {
		fmt.Println(err)
		return t
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Accept", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return t
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return t
	}

	fmt.Println(body)
	logs.Info(string(body))
	json.Unmarshal(body, &t)
	return t
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
func GetAccessToken() string {
	url := "https://aip.baidubce.com/oauth/2.0/token"
	postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", API_KEY, SECRET_KEY)
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postData))
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	accessTokenObj := map[string]string{}
	json.Unmarshal([]byte(body), &accessTokenObj)
	return accessTokenObj["access_token"]
}
